package com.xiaotu.service.login.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.xiaotu.dao.common.CommonMapper;
import com.xiaotu.dto.WxPhoneDto;
import com.xiaotu.dto.WxUserDto;
import com.xiaotu.dto.WxUserPhoneDto;
import com.xiaotu.service.login.LoginService;
import com.xiaotu.service.user.WxUserService;
import com.xiaotu.util.TokenUtil;
import com.xiaotu.util.WechatDecryptDataUtil;
import com.xiaotu.util.WxUtil;
import com.xiaotu.vo.LoginReturnVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhangxiao
 * @create 2021-08-16 14:38
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private WxUserService wxUserService;

    @Autowired
    private CommonMapper commonMapper;

    @Override
    public Object login(WxPhoneDto wxPhoneDto) {
        Validator.validateTrue(StrUtil.isNotBlank(wxPhoneDto.getCode()), "Code不能为空");
        JSONObject jsonObject = new JSONObject(WxUtil.getWxOpenIdSessionKey(wxPhoneDto.getCode()));
        TokenUtil.PayloadData.setKeyVal(WxUtil.VX_SESSION_USER, jsonObject.toBean(Map.class));
        Map<String, String> res = new HashMap<>();
        res.put("token", TokenUtil.createToken(TokenUtil.PayloadData.toJson()));
        return res;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Object wxPhone(HttpServletRequest request, WxPhoneDto wxPhoneDto) {
        Validator.validateTrue(StrUtil.isNotBlank(wxPhoneDto.getEncryptedData()), "EncryptedData不能为空");
        Validator.validateTrue(StrUtil.isNotBlank(wxPhoneDto.getIv()), "Iv不能为空");
        Validator.validateTrue(StrUtil.isNotBlank(wxPhoneDto.getNickName()), "nickName不能为空");
        Validator.validateTrue(StrUtil.isNotBlank(wxPhoneDto.getAvatarUrl()), "avatarUrl不能为空");
        Map<String, Object> gloGlobalCache = TokenUtil.getGloGlobalCache(request, WxUtil.VX_SESSION_USER, Map.class);
        String data = WechatDecryptDataUtil.decryptData(wxPhoneDto.getEncryptedData(), gloGlobalCache.get("session_key").toString(), wxPhoneDto.getIv());
        JSONObject wxPhone = new JSONObject(data);
        WxUserDto wxUserDtoExsit = (WxUserDto) wxUserService.queryWxUserByOpenId(gloGlobalCache.get("openid").toString());
        if (ObjectUtil.isNull(wxUserDtoExsit)) {
            wxUserDtoExsit = new WxUserDto(null, gloGlobalCache.get("openid").toString(), wxPhone.getStr("phoneNumber"), wxPhoneDto.getNickName(), wxPhoneDto.getAvatarUrl(), 0, 0);
            wxUserService.insertWxUser(wxUserDtoExsit);
        } else {
            wxUserDtoExsit.setNickName(wxPhoneDto.getNickName());
            wxUserDtoExsit.setAvatarUrl(wxPhoneDto.getAvatarUrl());
            wxUserDtoExsit.setWxPhone(wxPhone.getStr("phoneNumber"));
            wxUserService.updateWxUser(wxUserDtoExsit);
        }
        WxUserPhoneDto wxUserPhoneDto = commonMapper.getWxUserPhoneDto(wxUserDtoExsit.getUserId());
        LoginReturnVo returnVo = new LoginReturnVo();
        BeanUtil.copyProperties(wxUserPhoneDto, returnVo);
        return returnVo;
    }

}
